package com.diors.commons.network;

import com.diors.commons.log.DiorsLogger;
import com.diors.commons.thread.SelecterWrapper;

/**
 * 接收包
 * @author	darren.ouyang
 * @data	2013-9-11
 */
public abstract class ReceivablePacket extends SelecterWrapper
{

	static DiorsLogger log = DiorsLogger.getLogger(ReceivablePacket.class);
	
	/* 网络连接 */
	protected DiorsConnection conn;
	
	/* 流 */
	protected DiorsBuffer buffer;
	
	public ReceivablePacket (DiorsConnection conn, DiorsBuffer dbuffer)
	{
		this.conn = conn;
		this.buffer = dbuffer;
	}
	
	/**
	 * 读取接收包
	 * @return
	 * @create	2013-9-11	darren.ouyang
	 */
	protected final boolean read ()
	{
		try
		{
			readImpl();
			
			if (this.getRemaining() > 0)
				log.debug(new StringBuilder("数据包").append(this).
						append("没有读取完整。").toString());
			
			return Boolean.TRUE;
		}
		catch (Exception e)
		{
			log.error(new StringBuilder("读取数据包出错：").append(this).toString(), e);
			return Boolean.FALSE;
		}
	}
	
	protected abstract void readImpl ();
	
	/**
	 * 解包处理方法
	 * @param buffer	网络流
	 * @return
	 * @create	2013-9-11	darren.ouyang
	 */
	public abstract boolean processData ();
	
	/**
	 * 获取连接
	 * @return
	 * @create	2013-9-11	darren.ouyang
	 */
	protected DiorsConnection getConnection()
	{
		return conn;
	}
	
	/**
	 * 获得字数据包字节缓冲流剩余的字节数
	 * @return			剩余的字节数
	 */
	protected int getRemaining()
	{
		return this.buffer.getBuffer().readableBytes();
	}
	
	public DiorsConnection getConn ()
	{
		return conn;
	}
}
